/**
 * Copyright (c) 2020 铭软科技(mingsoft.net)
 * 本软件及相关文档文件（以下简称“软件”）的版权归 铭软科技 所有
 * 遵循铭软科技《保密协议》
 */
package net.mingsoft.mwebsite.biz.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import net.mingsoft.base.biz.impl.BaseBizImpl;
import net.mingsoft.base.entity.BaseEntity;
import net.mingsoft.basic.constant.e.ManagerAdminEnum;
import net.mingsoft.basic.dao.*;
import net.mingsoft.basic.util.BasicUtil;
import net.mingsoft.mwebsite.dao.IWebsiteRoleDao;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.mingsoft.base.dao.IBaseDao;
import net.mingsoft.basic.entity.ManagerEntity;
import net.mingsoft.basic.entity.RoleEntity;
import net.mingsoft.basic.entity.RoleModelEntity;
import net.mingsoft.mwebsite.biz.IWebsiteBiz;
import net.mingsoft.mwebsite.dao.IWebsiteDao;
import net.mingsoft.mwebsite.entity.WebsiteEntity;

import java.util.Date;

/**
 * 网站基本信息业务层实现类
 *
 * @author 铭软团队
 * @version 版本号：100-000-000<br/>
 *          创建日期：2012-03-15<br/>
 *          历史修订：<br/>
 */
@Service("websiteBiz")
public class WebsiteBizImpl extends BaseBizImpl<IWebsiteDao, WebsiteEntity> implements IWebsiteBiz {

	/**
	 * 声明IAppDao持久化层
	 */
	@Autowired
	private IWebsiteDao websiteDao;

	@Autowired
	private IManagerDao managerDao;
	@Autowired
	private IModelDao modelDao;
	@Autowired
	private IWebsiteRoleDao websiteRoleDao;

	@Autowired
	private IRoleModelDao roleModelDao;

	@Autowired
	private IRoleDao roleDao;

	@Override
	public int saveEntity(BaseEntity baseEntity) {
		WebsiteEntity websiteEntity = (WebsiteEntity) baseEntity;
		//oracle不支持insert自增长的返回值，使用没有返回值的方法
//		websiteDao.saveEntityNotRes(websiteEntity);
		save(websiteEntity);
		String query = "INSERT INTO mdiy_dict (dict_value,dict_label,dict_type,dict_description,dict_remarks,app_id,del) (SELECT  dict_value,dict_label,dict_type,dict_description,dict_remarks,{},del FROM mdiy_dict WHERE del=3 and app_id={})";
		websiteRoleDao.excuteSql(StrUtil.format(query,websiteEntity.getWebsiteId(),BasicUtil.getApp().getAppId()));
		//oracle不支持返回自增长id
		return websiteEntity.getWebsiteId();
	}

	@Override
	public void deleteEntity(int id) {
		super.deleteEntity(id);
		String del = "DELETE FROM mdiy_dict WHERE app_id={}";
		websiteRoleDao.excuteSql(StrUtil.format(del,id));
		String role = "DELETE FROM role WHERE app_id={}";
		websiteRoleDao.excuteSql(StrUtil.format(role,id));

	}

	/**
	 * 获取应用持久化层
	 *
	 * @return appDao 返回应用持久化层
	 */
	@Override
	protected IBaseDao getDao() {
		// TODO Auto-generated method stub
		return websiteDao;
	}

	@Override
	public int countByUrl(String websiteUrl) {
		// TODO Auto-generated method stub
		return websiteDao.countByUrl(websiteUrl);
	}

	@Override
	public WebsiteEntity getByUrl(String url) {
		// TODO Auto-generated method stub
		return websiteDao.selectOne(Wrappers.<WebsiteEntity>lambdaQuery().like(WebsiteEntity::getWebsiteUrl, url));
	}

	@Override
	public int saveRole(RoleEntity role) {
		// TODO Auto-generated method stub
		return this.websiteDao.saveRole(role);
	}

	@Override
	public void save(WebsiteEntity website, ManagerEntity manager, int[] models) {
		// TODO Auto-generated method stub

		RoleEntity role = new RoleEntity();
		role.setRoleName(manager.getManagerNickName());
		Subject subject = SecurityUtils.getSubject();
		ManagerEntity _manager = (ManagerEntity) subject.getPrincipal();
		role.setCreateBy(_manager.getId());
		role.setCreateDate(new Date());

		/*
		* 使用oracle的自增长主键，需要使用mybatis-plus的insert方法进行保存才会返回正确的id
		* 但该方法会被多住户拦截，需要在下面重新更新一下appId，使用不被多住户拦截的dao方法（@SqlParser(filter = true)）
		* */
		roleDao.insert(role);
		roleDao.excuteSql(StrUtil.format("update role set app_id={} where id={}",website.getWebsiteId(),role.getId()));

		manager.setCreateBy(_manager.getId());
		manager.setCreateDate(new Date());
		manager.setRoleId(role.getIntId());
		managerDao.insert(manager);
		if (models != null) {
			for (int id : models) {
				RoleModelEntity roleModel = new RoleModelEntity();
				roleModel.setModelId(id);
				roleModel.setRoleId(role.getIntId());
				roleModelDao.insert(roleModel);
			}
		}
		//更新缓存
		managerDao.updateCache();
		roleDao.updateCache();
		roleModelDao.updateCache();
	}

	@Override
	public void updateManager(ManagerEntity manager, int[] models) {
		// TODO Auto-generated method stub
		managerDao.updateById(manager);
		roleModelDao.deleteByRoleId(manager.getRoleId());
		if (models != null) {
			for (int id : models) {
				RoleModelEntity roleModel = new RoleModelEntity();
				roleModel.setModelId(id);
				roleModel.setRoleId(manager.getRoleId());
				roleModelDao.insert(roleModel);
			}
		}
		//更新缓存
		managerDao.updateCache();
		roleModelDao.updateCache();
		modelDao.updateCache();

	}

	/**
	 * 通过站点id获取管理员
	 * @param websiteId 站点id
	 */
	@Override
	public ManagerEntity getManageByAppId(Integer websiteId) {
		BasicUtil.startPage(1 ,1, false);
		RoleEntity roleEntity = websiteRoleDao.getEntityByAppId(websiteId);
		if (roleEntity == null) {
			return null;
		}
		ManagerEntity managerEntity = new ManagerEntity();
		managerEntity.setRoleId(roleEntity.getIntId());
		managerEntity.setManagerAdmin(ManagerAdminEnum.SUPER.toString());
		managerEntity = managerDao.getByEntity(managerEntity);

		return managerEntity;
	}


}
